'use strict';

const Controller = require('egg').Controller;
//egg-mysql
const mysql = require('mysql')
//token
const jwt = require('jsonwebtoken')
//mock
class HomeController extends Controller {

  //登录
  async login() {
    const { ctx, app } = this
    const { username, password } = ctx.request.body
    const data = await app.mysql.get('login', { username, password })
    const token = jwt.sign(username, 'lm')
    if (data) {
      ctx.body = {
        code: 1,
        msg: '登录成功',
        token
      }
    } else {
      ctx.body = {
        code: 0,
        msg: '登录失败'
      }
    }
  }
  // async index() {
  //   const { ctx, app } = this;
  //   await MockDate.forEach(item => {
  //     app.mysql.insert('mocklist', { url: item.url, title: item.title, desc: item.desc })
  //     ctx.body = {
  //       code: 200,
  //       msg: "成功"
  //     }
  //   })
  // }
  //渲染数据
  async getlist() {
    const { ctx, app } = this;
    const data = await app.mysql.select('mocklist')
    ctx.body = {
      code: 200,
      data,
    }
  }

  //房源渲染数据
  async tableData() {
    const { ctx, app } = this;
    const data = await app.mysql.select('tableData')
    ctx.body = {
      code: 200,
      data,
    }
  }
  //团购渲染数据
  async shoplist() {
    const { ctx, app } = this;
    const data = await app.mysql.select('shoplist')
    ctx.body = {
      code: 200,
      data,
    }
  }
  //删除
  async dellist() {
    const { ctx, app } = this;
    const { id } = ctx.request.body;
    app.mysql.delete('tabledata', { id })
    ctx.body = {
      code: 200,
      msg: "删除成功"
    }
  }
  //删除
  async dellist() {
    const { ctx, app } = this;
    const { id } = ctx.request.body;
    app.mysql.delete('shoplist', { id })
    ctx.body = {
      code: 200,
      msg: "删除成功"
    }
  }
//搜索
  async search() {
    const { ctx, app } = this
    const { val } = ctx.request.body
    const data = await app.mysql.query(`select * from tableData where room like '%${val}%'`)

    ctx.body = {
      code: 200,
      data
    }
  }
  //新增
  async addlist(){
    const {ctx,app}=this;
    const {room,area,price,time,sort,type}=ctx.request.body;
    await app.mysql.insert("tabledata",{room,area,price,time,sort,type})

    ctx.body={
      code:200,
      msg:"添加成功"
    }
  }
  //筛选
   //筛选户型
   async screening1() {
    const { app, ctx } = this
    const { value } = ctx.request.body
    const data = await app.mysql.select("mocklist", { where: { state: value } })

    if (value === '户型') {
      ctx.body = {
        code: 1,
        data
      }
    } else {
      ctx.body = {
        code: 500,
        data
      }
    }
  };
}

module.exports = HomeController;
